<template>
  <view class="content">
    <van-nav-bar :title="navBarTitle" left-arrow @click-left="onClickLeft" id="navBar"> </van-nav-bar>
    <!-- <loading :loadingIsShow="loadingIsShow"></loading> -->
    <view class="main-container">
      <!-- 分类按钮 -->
      <view class="topBox">
        <view class="sort-menu">
          <view :class="[currentPIndex===index ? 'sort_option_selected ' :'' , 'sort_option']"
            v-for="(item, index) in allData" :key="index" :id="index" @click="changeSort(index, $event, item.name)">
            <view class="couponSpanText">{{ item.name }} <span style="margin-left: 14rpx;">({{
                filteredCouponCount[index] }})</span></view>
            <view class="bottomLine" v-if="currentPIndex===index"></view>
          </view>
        </view>

      </view>

      <scroll-view :refresher-enabled="false" class="scroll-content" @scroll="scrollPage" scroll-y :lower-threshold="80"
        show-scrollbar="false">

        <view class="scroll-box">
          <view class="mycoupon_box">
            <template v-if="myCouponList.length > 0">
              <view class="myCoupon listItem"
                :class="{'listItemBg':currentPIndex!==0,'borderRadius':item.isShow===false}"
                v-for="(item, index) in myCouponList" :key="index" :id="item.key">
                <view class="listItemTop">
                  <view class="itemLeft" :class="{'itemLeftGray':currentPIndex!==0}">
                    <view :class="[currentPIndex === 0 ? 'top' : 'shixiao']"> <span>￥</span> {{ item.money }} </view>
                    <view class="itemLeftMiddle">{{ item.limitations }}</view>
                    <view class="itemLeftButton" v-if="currentPIndex === 0 " @tap="toUseCoupon(item)">去使用</view>
                    <view class="outOfDate" v-if="currentPIndex === 1 ">已使用</view>
                    <view class="outOfDate" v-if="currentPIndex === 2 ">已过期</view>
                  </view>
                  <!-- <view class="line"></view> -->
                  <view class="itemRight" :class="{'itemRightGray':currentPIndex!==0}">
                    <view class="itemRightTop ">
                      <view class="couponType" :class="{ 'outDateType': currentPIndex !== 0 }">{{ item.couponType }} </view>
                      <view class="couponName" :class="{'actColor': currentPIndex !== 0 }">{{ item.name }}</view>
                    </view>
                    <view class="middle deadline">有效期{{ item.deadline }}</view>
                    <view class="shuoming term" @click="showDescription(item)">详细说明 <van-icon name="arrow-down"
                        size="12" color="#888888" style="margin-left: 4px;" /> </view>
                  </view>
                </view>
                <view class="listItemBottom" :class="{'listItemBottom_Bg': currentPIndex !== 0 }" v-if="item.isShow==true">
                  <view class="describ">·{{item.term}}</view>
                  <view class="describ" style="margin-top: 16rpx;" v-if="item.couponDesc">·{{item.couponDesc}}</view>
                </view>
              </view>
              <!-- 新增分类空状态提示 -->
              <!-- <template v-if="filteredCouponList.length === 0">
                <van-empty class="custom-image"
                  image="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/noCoupons.png"
                  :description="`暂无${allData[currentPIndex].name}优惠券`" />
              </template> -->
            </template>
            <template v-if="myCouponList.length === 0">
              <van-empty class="custom-image"
                image="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/noCoupons.png"
                :description="`暂无${allData[currentPIndex].name}优惠券`"  />
            </template>
          </view>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

  <script>
  import { topStyleWhite, topStyleBlack } from '@/utils/topColor'

  import { getUserAllCouponApi} from  '@/api/mine'
  
  export default {
    components: {

    },
    data() {
      return {
        navBarTitle: '我的优惠券',
        scrolling: false, // 顶部区域吸顶效果
        currentPIndex: 0,

        allData: [
          {
            id: 1,
            name: '待使用'
          },
          {
            id: 2,
            name: '已使用'
          },
          {
            id: 3,
            name: '已过期'
          },
        ],
        params: undefined,
        myCouponList: [
          // {
          //   id: 1,
          //   money: 20,
          //   isLimited: true,
          //   limitations: '满69可用',
          //   couponType: '品类券',
          //   name:'优惠券名称',
          //   term: '限指定商品可用',
          //   nokeyong:'特价商品不可用',
          //   deadline: '2024.02.12-2024.02.18',
          //   status:0,
          // },
          // {
          //   id: 2,
          //   money: 10,
          //   isLimited: true,
          //   limitations: '满45可用',
          //   couponType: '通用券',
          //   name:'优惠券名称',
          //   term: '限指定商品可用',
          //   nokeyong:'特价商品不可用',
          //   deadline: '2024.02.12-2024.02.18',
          //   status:1,
          // }
        ],
        noUseList: [],
        usedList: [],
        expiredList: [],
        expiredTotal: 0, // 已过期的总数量
        noUseTotal: 0, // 未使用的总数量
        usedTotal: 0, // 已使用的总数量
        isSelect: false,
        curPopup: 0,
        curFilter: '全部',
        currentId:-1,
        filteredCouponCount:{ 0:0, 1:0, 2:0 }
      }
    },
    onLoad(data) {
      // 取到路由携带的参数
      if (data != null) {
        this.params = JSON.parse(decodeURIComponent(data.params))
        console.log('params', this.params)

      }

    },
    onReady() {
      topStyleWhite()
      // this.myCouponList.forEach(item => {
      //   this.$set(item,'isShow',false)
      // });
      this.getMyCouponList()
    },

    computed: {
      // // 获取当前分类下的优惠券列表
      // filteredCouponList() {
      //   return this.myCouponList.filter(item => item.status === this.currentPIndex);
      // },
      // // 计算每个分类的优惠券数量
      // filteredCouponCount() {
      //   return this.allData.map((_, index) =>
      //     this.myCouponList.filter(item => item.status === index).length
      //   );
      // }
    },

    methods: {
        // 新增时间范围格式化方法
        formatDateRange(startTime, endTime) {
            if (!startTime || !endTime) return '有效期未知'
            let result = ''
            const now = new Date();
            const start = new Date(startTime)
            const end = new Date(endTime)
            const timeDiff = end - now;
            return `${start.getFullYear()}.${(start.getMonth() + 1).toString().padStart(2, '0')}.${start.getDate().toString().padStart(2, '0')} 至 ${end.getFullYear()}.${(end.getMonth() + 1).toString().padStart(2, '0')}.${end.getDate().toString().padStart(2, '0')}`
        },
        // 获取优惠券使用截止时间
        formatCouponEndData(endTime) {
            if (!endTime) return '有效期未知'
            const date = new Date(endTime);
            const year = date.getFullYear();
            const month = (date.getMonth() + 1).toString().padStart(2, '0');
            const day = date.getDate().toString().padStart(2, '0');
            const hours = date.getHours().toString().padStart(2, '0');
            const minutes = date.getMinutes().toString().padStart(2, '0');
            return `${year}年${month}月${day}日  ${hours}:${minutes}前可享`;
        },
      // scrolltolower () {
      //     if (this.totalPage <= this.contentData.length) {
      //         this.isLoadAll = true
      //         this.biaozhi = 0
      //         this.loadingText = '没有更多数据啦~'
      //     } else {
      //         this.abnormalDetailsParamas.pageNum++
      //         this.isLoadAll = true
      //         this.loadingText = '加载中...'
      //         this.biaozhi = 1
      //         this.getAbnormalDetailsMethod()
      //     }
      // },
      // 互动页面
      scrollPage(e) {
        console.log(e.detail.scrollTop, this.scrolling)
        if (e.detail.scrollTop > 25 && !this.scrolling) {
          this.scrolling = true
        } else if ((e.detail.scrollTop <= 25 && this.scrolling) || (e.detail.scrollTop <= 25 && !this.scrolling)) {
          this.scrolling = false
        }
      },

      onClickLeft() {
        uni.navigateBack()
      },
      // 页面顶部的tab
      changeSort(index, e) {
        this.currentPIndex = index
        this.curPopup = this.currentPIndex    // 弹窗部分的选项
        console.log(index, e)
        if (this.currentPIndex == 0) {
          this.myCouponList = this.noUseList
        } else if (this.currentPIndex == 1) {
          this.myCouponList = this.usedList
        } else if (this.currentPIndex == 2) {
          this.myCouponList = this.expiredList
        }
      },
      // 页面顶部 tab下的内容
      selectFilter(val, e, item) {
        this.curFilter = val
        console.log(val, e, item)
        if (item === '价格') {
          this.isSelect = !this.isSelect
        }
      },
      // 显示弹窗
      onClickSort() {
        this.popupShow = true
        topStyleWhite()
      },
      // 弹窗内点击事件
      onClickPopup(index, e) {
        console.log(index, e, '弹窗内点击事件')
        this.curPopup = index
        this.currentPIndex = index    //页面顶部的tab
      },
      // 隐藏弹窗
      closePopup() {
        this.popupShow = false
        topStyleBlack()
      },


      // 显示说明
      showDescription(item){
        console.log(item,'showDescription',item.isShow)
        this.currentId=item.id
        this.$set(item, 'isShow', !item.isShow)
      },

      // 去使用 
      toUseCoupon(item){
        console.log('去使用',item)
        const params = {
          pageSign:'coupon',
          item:item,
          minPrice:item.minPrice,
          useType:item.useType,
          titleDate:this.formatCouponEndData(item.endTime),
        }

        console.log(params,'params')
        uni.navigateTo({ url: '/pages/shangcheng/joinOrders?params='+encodeURIComponent(JSON.stringify(params)) })
      },

      // // 跳转商品详情
      // toGoodsDetail(item, val, id) {
      //   console.log(item, val, 'toGoodsDetail')
      //   const params = {}
      //   params.item = item
      //   params.id = id
      //   params.biaozhi = 'productList'

      //   uni.navigateTo({
      //     url:
      //       '/pages/shangcheng/goodsDetail?params=' +
      //       encodeURIComponent(JSON.stringify(params))
      //   })
      // },

      // refresherpulling () {
      //     if (!this.isrefresher) {
      //         this.tableInfo = []
      //         this.contentData = []
      //         this.totalPage = 0
      //         this.loadingText = ''
      //         this.isrefresher = true // 下拉加载，先让其变true再变false才能关闭
      //         this.abnormalDetailsParamas.pageNum = 1
      //         console.log(this.abnormalDetailsParamas.pageNum, 'pageNum')
      //         const interFace = this.getAbnormalDetailsMethod()
      //         Promise.all([interFace]).then(() => {
      //             // 关闭加载状态 (转动的圈)，需要一点延时才能关闭
      //             this.time = setTimeout(e => {
      //                 this.isrefresher = false
      //             }, 100)
      //         })
      //     }
      // },
      // onChangeSort(){
      //   if(this.curFilter!==2){
      //     this.curFilter===2
      //   }
      //   this.isSelect=!this.isSelect
      // },

      // 格式化优惠券数据
      formatCouponData(couponList) {
          return couponList.map(item => {
              return {
                  ...item,
                  deadline: this.formatDateRange(item.startTime, item.endTime),
                  couponType: item.useType === 1 ? '全场通用' : item.useType === 2 ? '商品券' : '品类券',
                  isShow: false,
                  limitations: item.minPrice > 0 ? `满${item.minPrice}可用` : '',
                  term: item.useType === 1 ? '全场通用' : item.useType === 2 ? '限指定商品可用' : '限指定品类可用'
              }
          })
      },
      // 接口
      getMyCouponList() {
        return new Promise((resolve, reject) => {
          getUserAllCouponApi().then((res) => {
            if (res.code === 200) {
              this.noUseList = this.formatCouponData(res.data?.noUseList || [])
              this.usedList = this.formatCouponData(res.data?.usedList || [])
              this.expiredList = this.formatCouponData(res.data?.expiredList || [])
              this.expiredTotal = res.data?.expiredTotal || 0
              this.noUseTotal = res.data?.noUseTotal || 0
              this.usedTotal = res.data?.usedTotal || 0
              this.filteredCouponCount = {
                0: this.noUseTotal,
                1: this.usedTotal,
                2: this.expiredTotal
              }
              if (this.currentPIndex ==0){
                this.myCouponList = this.noUseList
              }else if(this.currentPIndex ==1){
                this.myCouponList = this.usedList
              }else if(this.currentPIndex ==2){
                this.myCouponList = this.expiredList
              }
            
              resolve(res)
            } else {
              reject(res)
            }
          })
        })
      },


      // // 接口
      // getMyCouponList() {
      //   return new Promise((resolve, reject) => {
      //     getUserAllCouponApi().then((res) => {
      //       if (res.code === 200) {
      //         const userCouponList =res.data.ebStoreCouponUserList
      //         const couponList = res.data.ebStoreCouponList
      //         this.myCouponList = userCouponList.map(item => {
      //           // 通过couponId匹配list中的元素
      //           const couponInfo = couponList.find(c => c.id === item.couponId) || {}
      //           console.log(couponInfo, 'couponInfo')
      //           return {
      //             key:item.id,
      //             name:item.name,
      //             couponId:item.couponId,
      //             money:item.money,
      //             minPrice:item.minPrice,
      //             startTime:item.startTime,
      //             endTime:item.endTime,
      //             // ...item,
      //             // ...couponInfo, // 合并两个对象的字段
      //             useType: couponInfo.useType, //1 全场通用, 2 商品券, 3 品类券
      //             couponType: couponInfo.useType === 1? '全场通用' : couponInfo.useType === 2? '商品券' : '品类券',
      //             term: couponInfo.useType === 1? '全场通用' : couponInfo.useType === 2? '限指定商品可用' : '限指定品类可用',
      //             limitations: couponInfo.minPrice > 0 ? `满${couponInfo.minPrice}可用` : '',
      //             deadline: this.formatDateRange(item.startTime, item.endTime),
      //             isShow:false, //控制显示隐藏
      //             status:item.status,
      //             // instructions: couponInfo.instructions,
      //           }
      //         })
      //         resolve(res)
      //       } else {
      //         reject(res)
      //       }
      //     })
      //   })
      // },

    }
  }
  </script>
  
  <style lang="scss" scoped>
  .content {
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    height: 100vh;
    overflow: hidden;
    z-index: -2;
    background: #ffffff;
    background-size: 100%;
    // padding-bottom: calc(0rpx + env(safe-area-inset-bottom));
  }

  .main-container {
    background: #ffffff;
    overflow: hidden;
    // box-shadow: 0px 4px 10px rgba(61, 92, 153, 0.1);
    height: 100vh;
    display: flex;
    flex-direction: column;
    width: 100%;
  }


  .topBox {
    margin-top: 10px;
    margin-bottom: 12px;
    padding-left: 24px;
    padding-right: 24px;
    width: calc(100% - 48px);
    // padding-left: 11px;
    // padding-right: 11px;

    // 全部分类  menu
    .sort-menu {
      width: 100%;
      height: 44px;
      line-height: 44px;
      // margin-bottom: 18px;
      // display: flex;
      justify-content: space-around;
      align-items: center;
      text-align: center;
      vertical-align: middle;

      .sort_option {
        // flex: auto;
        font-size: 26rpx;
        height: 26rpx;
        line-height: 26rpx;
        cursor: pointer;
        display: inline-block;
        flex-direction: column;
        align-items: center;
        // overflow: hidden;
        padding: 14px 20px 6px;
      }

      .sort_option_selected {
        font-weight: bolder;
        line-height: 26rpx;
        font-size: 26rpx;
        padding: 10px 20px 8px;
      }

      .bottomLine {
        // width: 40rpx;
        height: 4rpx;
        background-color: rgba(255, 98, 3, 1);
        border-radius: 2px;
        margin-top: 14rpx;
        text-align: center;

      }

    }

    // // 按钮公用样式
    //     .item_option {
    //       line-height: 14px;
    //       font-size: 14px;
    //       text-align: left;
    //       color: #666666;
    //     }

    //     .item_option_selected {
    //       // font-weight: 900;
    //       font-weight: bolder;
    //       text-align: left;
    //       color: #111111;
    //     }


  }

  // 滚动
  .scroll-content {
    flex: 1;
    height: 1px;
  }

  .scroll-box {
    padding-left: 24px;
    padding-right: 24px;
    height: 100vh;
    // background: white;
    // background: palevioletred;
  }


  // 我的优惠券盒子
  .mycoupon_box {
    margin-top: 15px;
    // padding-bottom: 75px;

  }

  // 优惠券列表
  .listItem {
    -webkit-tap-highlight-color: transparent; /* 禁用点击高亮 */
    margin-bottom: 12px;
    // background: linear-gradient(180deg, rgba(255, 252, 250, 1) 100%, rgba(255, 252, 252, 0.62) 0%);
    background: #FFFCF9;
    border-radius: 5px 5px 0px 0px;
    transform: scale(1); /* 确保初始状态 */
    // transition: none; /* 禁用过渡效果 */
    transition: transform 0.1s ease;

    &:active {
      transform: scale(1);
    }

    .listItemTop {
      display: flex;
      align-items: center;
      text-align: left;

      .itemLeft {
        position: relative;
        padding-top: 17px;
        padding-bottom: 11px;
        display: flex;
        flex-direction: column;
        text-align: center;
        vertical-align: center;
        align-items: center;
        // width: 50%;
        width: 208rpx;
        border-radius: 5px 0px 0px 5px;
        background-color: #FFF2EA;
        border-right: 1px dashed #FFB695;

        .top {
          font-size: 40rpx;
          line-height: 40rpx;
          color: #FF6203;
          width: 100%;
          height: 40rpx;
          font-weight: bolder;

          span {
            font-family: 'Courier New', Courier, monospace;
          }
        }

        // 优惠券失效的面值样式
        .shixiao {
          color: #666666;
          font-size: 40rpx;
          line-height: 40rpx;
          width: 100%;
          height: 40rpx;
          font-weight: bolder;
        }

        .itemLeftMiddle {
          margin-top: 18rpx;
          font-size: 22rpx;
          line-height: 22rpx;
          height: 22rpx;
          color: #666666;
          width: 100%;
          text-align: center;
        }

        .itemLeftButton {
          background-color: #FF6203;
          color: #ffffff;
          font-size: 22rpx;
          line-height: 40rpx;
          height: 40rpx;
          width: 96rpx;
          border-radius: 40rpx;
          // padding-left: 16rpx;
          // padding-right: 16rpx;
          margin-top: 36rpx;
          text-align: center;
        }

        // 已过期按钮
        .outOfDate {
          background: #666666;
          color: #ffffff;
          font-size: 22rpx;
          line-height: 40rpx;
          height: 40rpx;
          width: 96rpx;
          border-radius: 40rpx;
          // padding-left: 16rpx;
          // padding-right: 16rpx;
          margin-top: 36rpx;
          text-align: center;
          // padding: 5px 13px;
          // border: 1px solid #D4D4D4;
        }
      }

      // .itemLeft:before {
      //     content: "";
      //     position: absolute;
      //     top: -3px;
      //     // left: -3px;
      //     right: -3px;
      //     // bottom: -2px;
      //     width: 10px;
      //     height: 10px;
      //     border-top-right-radius: 10px;
      //     border-bottom-left-radius: 40px;
      //     background-color: white;
      //     clip-path: polygon(0 0, 100% 0, 90% 100%, 0 100%);
      // }
      // .itemLeft:after {
      //     content: "";
      //     position: absolute;
      //     // top: -3px;
      //     // left: -3px;
      //     right: -3px;
      //     bottom: -3px;
      //     width: 10px;
      //     height: 10px;
      //     border-top-left-radius: 10px;
      //     // border-bottom-left-radius: 40px;
      //     background-color: white;
      //     clip-path: polygon(0 0, 100% 0, 90% 100%, 0 100%);
      // }
      .itemLeftGray {
        background-color: #EDEDED;
        border-right: 1px dashed #e5e5e5;
      }

      .line {
        // background-color: ;
      }

      .itemRight {
        position: relative;
        padding: 17px 24px;
        display: flex;
        flex-direction: column;
        text-align: left;
        align-items: center;
        padding-left: 52rpx;
        // width: 84%;
        border-radius: 0px 5px 5px 0px;
        background-color: #FFFAF7;

        .itemRightTop {
          width: 100%;
          display: flex;
          align-items: center;

          .couponType {
            // min-width: 78rpx;
            padding-left: 5px;
            padding-right: 5px;
            height: 36rpx;
            line-height: 36rpx;
            border-radius: 4rpx;
            background-color: transparent;
            color: #FF6203;
            font-size: 22rpx;
            text-align: center;
            border: 1px solid #FF6203;
          }

          .outDateType {
            //width: 78rpx;
            padding-left: 5px;
            padding-right: 5px;
            height: 36rpx;
            line-height: 36rpx;
            border-radius: 4rpx;
            color: #888888;
            background-color: transparent;
            font-size: 22rpx;
            text-align: center;
            border: 1px solid #D4D4D4;
          }

          // 优惠券名称
          .couponName {
            margin-left: 14rpx;
            text-align: left;
            font-size: 28rpx;
            color: #111111;
            line-height: 28rpx;
            height: 28rpx;
            max-width: 218rpx;
            white-space: nowrap;
            /* 防止文本换行 */
            overflow: hidden;
            /* 超出部分隐藏 */
            text-overflow: ellipsis;
            /* 显示省略号 */
          }

          .actColor {
            color: #888888;
          }
        }


        // 时间
        .deadline {
          width: 100%;
          font-size: 22rpx;
          text-align: left;
          color: #666666;
          line-height: 22rpx;
          margin-top: 20rpx;
        }

        // 限定商品使用
        .term {
          display: flex;
          align-items: center;
          width: 100%;
          line-height: 22rpx;
          font-size: 22rpx;
          color: #666666;
          margin-top: 38rpx;
          text-align: left;
        }

        // 过期失效时   时间的颜色
        .outDate {
          width: 100%;
          font-size: 13px;
          text-align: left;
          color: #B3B3B3;
          line-height: 13px;
          margin-top: 7px;
        }
      }

      // 优惠券左右中间的圆角
      .itemRight:before {
        content: "";
        position: absolute;
        top: -5px;
        left: -5px;
        // top:14px;
        // left: 248rpx;
        // right: -3px;
        // bottom: -2px;
        width: 10px;
        height: 10px;
        border-bottom-left-radius: 10px;
        border-bottom-right-radius: 10px;
        background-color: #ffffff;
        clip-path: polygon(0 0, 100% 0, 90% 100%, 0 100%);
      }

      .itemRight:after {
        //半圆
        content: "";
        position: absolute;
        left: -5px;
        bottom: 0px;
        width: 10px;
        height: 5px;
        border-top-right-radius: 50px;
        border-top-left-radius: 50px;
        background-color: #ffffff;
        // clip-path: polygon(0 0, 100% 0, 90% 100%, 0 100%);
      }

      .itemRightGray {
        background-color: #F5F5F5;
      }
    }

    .listItemBottom {
      height: 108rpx;
      display: flex;
      flex-direction: column;
      justify-content: center;
      padding-left: 24rpx;
      background: linear-gradient(180deg, rgba(255, 252, 250, 1) 100%, rgba(255, 252, 252, 0.62) 0%);

      .describ {
        font-size: 22rpx;
        color: #666666;
        line-height: 22rpx;
      }
    }

    .listItemBottom_Bg {
      background: #FAFAFA;
    }


    // 复选框的 圆圈
    .checked-img {
      height: 16px;
      width: 16px;
    }


    .iconDiv {
      .icon {
        width: 12px;
        height: 12px;
      }
    }
  }

  .listItemBg {
    background: #FAFAFA;
  }

  .borderRadius {
    border-radius: 5px;
  }

  .listItem:last-child {
    margin-bottom: 0px;
  }



  ::v-deep .van-nav-bar {
    // background-color: #f9f9f9 !important;
    z-index: 999 !important;
  }

  ::v-deep .van-nav-bar__left {
    width: 56px;
    height: 44px;
  }

  ::v-deep #navBar .van-icon {

    color: #242629 !important;
  }


  ::v-deep .van-nav-bar__title {
    font-size: 14px;
    color: #333333;
  }

  //   .van-empty {
  //     padding: 40px 0;
  //     .custom-image {
  //         width: 200px;
  //         height: 150px;
  //     }
  // }
  ::v-deep .van-empty__image {
    width: 150px;
    height: 100px;

  }
::v-deep .shuoming .van-icon {
   -webkit-tap-highlight-color: transparent;
    transform: scale(1);
    transition: none;
}


  .pl15 {
    padding-left: 15px;
  }

  .pr15 {
    padding-right: 15px;
  }
</style>
  